package com.dhz.common.solr.server;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.LBHttpSolrClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import java.net.MalformedURLException;

/**
 * HttpSolrClient的工厂实现类
 *
 * @author Fyduan
 */
public class HttpSolrClientFactoryBean extends HttpSolrClientFactory implements FactoryBean<SolrClient>, InitializingBean, DisposableBean {

    private static final String SERVER_URL_SEPARATOR = ",";
    private String url;
    private Integer timeout;
    private Integer maxConnections;

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(url);
        initSolrClient();
    }

    private void initSolrClient() {
        if (this.url.contains(SERVER_URL_SEPARATOR)) {
            createLoadBalancedHttpSolrClient();
        } else {
            createHttpSolrClient();
        }
    }

    private void createHttpSolrClient() {
        HttpSolrClient httpSolrClient = new HttpSolrClient(this.url);
        if (timeout != null) {
            httpSolrClient.setConnectionTimeout(timeout);
        }
        if (maxConnections != null) {
            httpSolrClient.setMaxTotalConnections(maxConnections);
        }
        this.setSolrClient(httpSolrClient);
    }

    private void createLoadBalancedHttpSolrClient() {
        try {
            LBHttpSolrClient lbHttpSolrClient = new LBHttpSolrClient(StringUtils.split(this.url, SERVER_URL_SEPARATOR));
            if (timeout != null) {
                lbHttpSolrClient.setConnectionTimeout(timeout);
            }
            this.setSolrClient(lbHttpSolrClient);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Unable to create Load Balanced Http Solr Server", e);
        }
    }

    @Override
    public SolrClient getObject() throws Exception {
        return getSolrClient();
    }

    @Override
    public Class<?> getObjectType() {
        if (getSolrClient() == null) {
            return HttpSolrClient.class;
        }
        return getSolrClient().getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }

    public void setMaxConnections(Integer maxConnections) {
        this.maxConnections = maxConnections;
    }

}
